using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net;
using OpenWaves.ActivityFeed.Web.Handler;

namespace OpenWaves.ActivityFeed.Web.Modules
{
    public class LikesModule : RestModule
    {
        public LikesModule(IActivityFeedService activityFeedService, IUserIdentityProvider identityProvider, IUserProfileProvider userProfileProvider)
        {
            Contract.Requires<ArgumentNullException>(activityFeedService != null);
            Contract.Requires<ArgumentNullException>(userProfileProvider != null);

            this.Post("/activityFeed/updates/{updateId}/likes", (request, p) => 
                                                    {
                                                        string updateId = p["updateId"];
                                                        Contract.Assert(String.IsNullOrEmpty(updateId) == false);

                                                        Update update = activityFeedService.GetUpdate(Url.Decode(updateId));
                                                        if (update == null)
                                                            return new HttpResult(HttpStatusCode.NotFound);
                
                                                        var publisherId = identityProvider.Identity.Name;

                                                        var like = update.AddLike(publisherId);

                                                        var likeDto = LikeEntryDto.FromLike(like, userProfileProvider);

                                                        return new JsonResult(new { result = "ok", value = likeDto });
                                                    });

            this.Delete("/activityFeed/updates/{updateId}/likes", (request, p) => 
                                                      {
                                                          string updateId = p["updateId"];
                                                          Contract.Assert(String.IsNullOrEmpty(updateId) == false);

                                                          Update update = activityFeedService.GetUpdate(Url.Decode(updateId));
                                                          if (update == null)
                                                            return new HttpResult(HttpStatusCode.NotFound);

                                                          update.RemoveLike(identityProvider.Identity.Name);

                                                          return new JsonResult(new { result = "ok" });
                                                      });
        }
    }
}